<template>
  <div class="container">
    <el-form ref="dataForm" :model="conModel" label-width="72px" size="mini" class="search_content">
      <el-row :gutter="24">
        <el-col :span="4" class="common_input">
          <el-form-item label="关键词:">
            <el-input v-model="conModel.SearchKey" clearable placeholder="" @keyup.enter.native="getList('search')" />
          </el-form-item>
        </el-col>
        <el-col :span="4" class="common_input">
          <el-form-item label="角色名称:">
            <el-input v-model="conModel.Name" clearable placeholder="请输入角色名称" @keyup.enter.native="getList('search')" />
          </el-form-item>
        </el-col>
        <el-col :span="1" class="common_query">
          <el-button size="mini" @click="getList('search')">
            查询
          </el-button>
        </el-col>
        <div class="common_right_btn common_query">
          <el-col :span="1">
            <el-button @click="addPopup"><span>新增</span></el-button>
          </el-col>
        </div>
      </el-row>
    </el-form>
    <div class="table_content">
      <el-table
        v-loading="listLoading"
        :data="list"
        fit
        style="width: 100%;"
        :stripe="true"
      >
        <el-table-column align="center" label="角色名称">
          <template slot-scope="scope">
            {{ scope.row.p.RoleName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="超级管理员">
          <template slot-scope="scope">
            {{ IsState(scope.row.p.SuperAdmin) }}
          </template>
        </el-table-column>
        <el-table-column label="角色权限列表" align="center" width="500px">
          <template slot-scope="scope">
            <el-tooltip class="block_content_item" effect="light" :content="RightToolTip(scope.row.p.RoleRights)" placement="bottom" popper-class="test_tooltip">
              <span class="block_content">{{ RightInfo(scope.row.p.RoleRights) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注">
          <template slot-scope="scope">
            {{ scope.row.p.Remark }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="建档时间">
          <template slot-scope="scope">
            {{ scope.row.p.BuildTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <span class="common_operation" @click="detailsPopup(row)">详情</span>
            <span class="common_operation" @click="editPopup(row)">编辑</span>
            <span class="common_operation" @click="deletePopup(row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total>0" class="my_pagination" :total="total" :PageIndex.sync="Parameter.PageIndex" :PageSize.sync="Parameter.PageSize" @pagination="getList" />
    <el-dialog :title="popupTitle[popupTitleKey]" :visible.sync="dialogFormVisible" class="newel-dialog common_add_edit_popup_two role_popup">
      <div class="el-dialog__body">
        <el-form ref="dataForm" :rules="rules" :model="temp" class="demo-ruleForm" label-width="120px" style="width: 100%; margin:0 auto;">
          <el-row :gutter="24">
            <el-col :span="10">
              <div class="grid-content bg-purple">
                <el-form-item label="角色名称:" prop="RoleName">
                  <el-input v-model="temp.RoleName" type="text" placeholder="请输入角色名称" />
                </el-form-item>
                <!-- <el-form-item label="超级管理员:" prop="SuperAdmin">
                  <el-checkbox v-model="temp.SuperAdmin" @change="Right(temp.SuperAdmin)" />
                </el-form-item> -->
              </div>
            </el-col>
            <el-col :span="10" :offset="3">
              <div class="grid-content bg-purple">
                <el-form-item label="备注:" prop="Remark">
                  <el-input v-model="temp.Remark" />
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="23">
              <el-form-item label="角色权限列表:" prop="RoleRights">
                <el-table
                  v-loading="listLoading"
                  :data="SuperNoList"
                  border
                  fit
                  highlight-current-row
                  style="width: 100%;"
                >
                  <el-table-column label="一级菜单" align="center" width="120px">
                    <template slot-scope="scope">
                      <el-checkbox :key="scope.row.RightNo" v-model="parentRoleArr" :label="scope.row.RightNo" @change="rightCheckbox(scope.row.RightNo)">{{ scope.row.RightName }}</el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column label="子菜单" align="center">
                    <template slot-scope="scope">
                      <el-checkbox-group v-model="childRoleArr" @change="grounpValue">
                        <template v-for="site in scope.row.son">
                          <el-checkbox :key="site.RightNo" :label="site.RightNo">{{ site.RightName }}</el-checkbox>
                        </template>
                      </el-checkbox-group>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <hr class="common_popup_border_bottom">
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="add_edit_btn cancel" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button class="add_edit_btn determine" type="primary" @click="popupTitleKey==='add'?AddRoleInfo():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogFormVisibleDelete"
      class="common_delete_popup"
      :modal-append-to-body="false"
    >
      <div slot="title" class="header-title">
        <span class="title-name"><i class="el-icon-warning delete_icon" /></span>
        <span class="title-age">系统角色</span>
      </div>
      <span class="delete_tips">系统角色信息删除后，不可恢复，是否继续删除?</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="cancel" @click="dialogFormVisibleDelete = false">取消</el-button>
        <el-button class="delete" type="primary" @click="DeleteRoleInfo()">删除</el-button>
      </span>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog title="系统角色详情" :visible.sync="dialogDetails" class="newel-dialog details_pupop common_details">
      <div class="el-dialog__body">
        <el-form ref="dataForm" :model="tempDetails" class="demo-ruleForm common_popup" label-width="120px">
          <div class="common_details_child" />
          <el-row :gutter="24">
            <el-col :span="10" :offset="2">
              <div class="grid-content bg-purple">
                <el-form-item label="角色名称:">
                  <span> {{ tempDetails.RoleName }} </span>
                </el-form-item>
                <el-form-item label="超级管理员:">
                  <span> {{ IsState(tempDetails.SuperAdmin) }} </span>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="10" :offset="1">
              <div class="grid-content bg-purple">
                <el-form-item label="备注:">
                  <span> {{ tempDetails.Remark }} </span>
                </el-form-item>
                <el-form-item label="建档时间:">
                  <span> {{ tempDetails.BuildTime | dateFormat }} </span>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="20" :offset="2">
              <div class="grid-content bg-purple">
                <el-form-item label="角色权限列表:">
                  <span> {{ tempDetails.RoleRights !== undefined ? RightInfo(tempDetails.RoleRights) : '' }} </span>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="retrun_btn" @click="dialogDetails = false">
          返回
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { GetRoleInfo, AddRoleInfo, DeleteRoleInfo, GetRightInfo } from '@/api/basics'

export default {
  name: 'Role',
  components: {
    Pagination
  },
  data() {
    return {
      Parameter: {
        PageSize: 10,
        PageIndex: 1,
        OrderBy: 'BuildTime',
        isDesc: true
      },
      conModel: {
        Name: '',
        SearchKey: ''
      },
      conModelCopy: {},
      temp: {
        RoleId: 0,
        RoleName: '',
        RoleRights: '[]',
        SuperAdmin: '',
        Remark: ''
      },
      searchkey: '', // 删除组件
      popupTitleKey: '',
      popupTitle: {
        add: '新增角色信息',
        edit: '编辑角色信息'
      },
      listLoading: false,
      dialogFormVisible: false,
      dialogFormVisibleDelete: false,
      list: [],
      total: 0,
      tempDetails: [],
      dialogDetails: false,
      rules: {
        RoleName: [
          { required: true, message: '请输入角色名称', trigger: 'change' }
        ]
      },
      childRoleArr: [],
      RightInfoList: [],
      rightNo: [],
      SuperNoList: [],
      parentRoleArr: [],
      childRoleObj: [],
      RoleIdLogin: ''
    }
  },
  created() {
    this.RoleIdLogin = localStorage.getItem('RoleId') // 验证是否能编辑当前登录帐号
    this.getList()
    this.GetRightInfo()
  },
  methods: {
    getList(init) {
      if (init === 'search') {
        this.Parameter.PageIndex = 1
        this.conModelCopy = {}
      }
      if (this.conModel.Name.trim() !== '' && init === 'search') {
        this.conModelCopy.Name = this.conModel.Name.trim()
      }
      if (this.conModel.SearchKey.trim() !== '' && init === 'search') {
        this.conModelCopy.SearchKey = this.conModel.SearchKey.trim()
      }
      this.listLoading = true
      var Parameter = {
        ...this.Parameter,
        ...this.conModelCopy
      }
      GetRoleInfo(Parameter).then(res => {
        this.list = res.Data
        this.total = res.Total
        this.listLoading = false
      })
    },
    addPopup() {
      this.popupTitleKey = 'add'
      this.childRoleArr = []
      this.parentRoleArr = []
      this.childRoleObj = []
      this.resetTemp()
      this.dialogFormVisible = true
      this.GetRightInfo()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    AddRoleInfo() {
      var arr = []
      this.parentRoleArr.map(key => arr.push({
        RightNo: this.originRoleData[key].RightNo,
        SuperNo: '0',
        RightName: this.originRoleData[key].RightName
      }))
      let rightArr = [
        ...arr, 
        ...this.childRoleObj
      ]
      let rightNoArr = []
      rightArr.map(item => {
        rightNoArr.push(item.RightNo)
      })
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp = {
            ...this.temp,
            SuperAdmin: this.temp.SuperAdmin ? 1 : 0,
            RoleRights: JSON.stringify(rightNoArr)
          }
          AddRoleInfo(this.temp).then((res) => {
            if (res.State === 'success') {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getList()
              this.resetTemp()
            }
          })
        }
      })
    },
    editPopup(row) {
      if (row.p.SuperAdmin === 1) {
        this.$message({
          message: '此角色为超级管理员，无法编辑',
          type: 'error'
        })
        return
      }
      if (row.p.RoleId == this.RoleIdLogin) {
        console.log('1test')
        this.$message({
          message: '此角色是当前登录帐号绑定的角色，无法编辑',
          type: 'error'
        })
        return
      }

      this.popupTitleKey = 'edit'
      this.dialogFormVisible = true
      this.childRoleArr = []
      this.parentRoleArr = []
      this.childRoleObj = []
      this.temp = Object.assign({}, row.p)
      var RoleRights = JSON.parse(this.temp.RoleRights)
      this.GetRightInfo()
      if (RoleRights) {
        for (var i = 0; i < RoleRights.length; i++) {
          for (var j = 0; j < this.RightInfoList.length; j++) {
            if (RoleRights[i] === this.RightInfoList[j].RightNo) {
              if(this.RightInfoList[j].son !== undefined) {
                this.parentRoleArr.push(this.RightInfoList[j].RightNo)
              } else {
                  this.childRoleArr.push(this.RightInfoList[j].RightNo)
                  this.childRoleObj.push({
                    RightNo: this.RightInfoList[j].RightNo,
                    SuperNo: this.RightInfoList[j].SuperNo,
                    RightName: this.RightInfoList[j].RightName
                  })
              }
            }
          }

          // if (RoleRights[i].SuperNo === '0') {
          //   this.parentRoleArr.push(RoleRights[i].RightNo)
          // } else {
          //   this.childRoleArr.push(RoleRights[i].RightNo)
          //   this.childRoleObj.push({
          //     RightNo: RoleRights[i].RightNo,
          //     SuperNo: RoleRights[i].SuperNo,
          //     RightName: RoleRights[i].RightName
          //   })
          // }
        }
      }
      if (row.p.SuperAdmin == 1) {
        this.temp.SuperAdmin = true
      } else {
        this.temp.SuperAdmin = false
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      var arr = []
      this.parentRoleArr.map(key => arr.push({
        RightNo: this.originRoleData[key].RightNo,
        SuperNo: '0',
        RightName: this.originRoleData[key].RightName
      }))
      let rightArr = [
        ...arr, 
        ...this.childRoleObj
      ]
      let rightNoArr = []
      rightArr.map(item => {
        rightNoArr.push(item.RightNo)
      })
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          delete this.temp.OperatorInfo
          this.temp = {
            ...this.temp,
            SuperAdmin: this.temp.SuperAdmin ? 1 : 0,
            RoleRights: JSON.stringify(rightNoArr)
          }
          AddRoleInfo(this.temp).then((res) => {
            if (res.State === 'success') {
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getList()
              this.resetTemp()
            }
          })
        }
      })
    },
    deletePopup(row) {
      if (row.p.SuperAdmin === 1) {
        this.$message({
          message: '此角色为超级管理员，无法删除',
          type: 'error'
        })
        return
      }
      this.dialogFormVisibleDelete = true
      this.temp = Object.assign({}, row)
    },
    DeleteRoleInfo() {
      DeleteRoleInfo({ searchkey: this.temp.p.RoleId }).then((res) => {
        if (res.State === 'success') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }
        this.getList()
      })
      this.dialogFormVisibleDelete = false
    },
    detailsPopup(row) {
      this.tempDetails = Object.assign({}, row.p)
      this.dialogDetails = true
    },
    resetTemp() {
      this.temp = {
        RoleId: 0,
        RoleName: '',
        RoleRights: '[]',
        SuperAdmin: '',
        Remark: ''
      }
    },
    IsState(value) {
      switch (value) {
        case 0:
          return '否'
        case 1:
          return '是'
        default:
          return value
      }
    },
    RightInfo(no) {
      if (no === '[]' || no === null || no === 'null') {
        return '暂无数据'
      }
      var val = JSON.parse(no)
      var name = []
      for(let i = 0; i< val.length;i++) {
        for(let j = 0; j<this.RightInfoList.length; j++) {
          if(val[i] == this.RightInfoList[j].RightNo) {
            name.push(this.RightInfoList[j].RightName)
          }
        }
      }
      return name
    },
    RightToolTip(no) {
      if (no === '[]' || no === null || no === 'null') {
        return '暂无数据'
      }
      var val = JSON.parse(no)
      var name = []
      for(let i = 0; i< val.length;i++) {
        for(let j = 0; j<this.RightInfoList.length; j++) {
          if(val[i] == this.RightInfoList[j].RightNo) {
            name.push(this.RightInfoList[j].RightName)
          }
        }
      }
      return JSON.stringify(name)
    },
    grounpValue(data) {
      // 单个勾选框，当二级菜单全都选，一级菜单选中，当二级菜单不全都选，一级菜单不选中，
      this.childRoleObj = []
      var objectValues = Object.values(this.originRoleData)
      objectValues.map(item => {
        this.originRoleData[item.RightNo].num = 0
      })
      objectValues.map(item => {
        item.son.map(childItem => {
          data.map(dataItem => {
            if (dataItem === childItem.RightNo) {
              this.childRoleObj.push({
                RightNo: dataItem,
                SuperNo: childItem.SuperNo,
                RightName: childItem.RightName
              })
              this.originRoleData[item.RightNo].num = this.originRoleData[item.RightNo].num + 1
              if (this.originRoleData[item.RightNo].num === this.originRoleData[item.RightNo]['son'].length) {
                this.parentRoleArr.push(item.RightNo)
              } else {
                if (this.parentRoleArr.indexOf(item.RightNo) !== -1) {
                  this.parentRoleArr.splice(this.parentRoleArr.indexOf(item.RightNo), 1)
                }
              }
            }
          })
        })
      })
    },
    rightCheckbox(key) {
      if (this.parentRoleArr.includes(key)) {
        // 不选中
        this.originRoleData[key].son.map(item => {
          if (!this.childRoleArr.includes(item.RightNo)) {
            this.childRoleObj.push({
              RightNo: item.RightNo,
              SuperNo: key,
              RightName: item.RightName
            })
            this.childRoleArr.push(item.RightNo)
          }
        })
      } else {
        // 选中
        this.originRoleData[key].son.map(item => {
          var index = this.childRoleArr.indexOf(item.RightNo)
          this.childRoleArr.splice(index, 1)
          this.childRoleObj.splice(index, 1)
        })
      }
    },
    GetRightInfo() {
      var Parameter = {
        PageSize: 9999,
        PageIndex: 1,
        IsDesc: true,
        OrderBy: ''
      }
      GetRightInfo(Parameter).then(res => {
        this.RightInfoList = res.Data
        this.rightNo = this.RightInfoList.map(item => item.RightNo).join(',').split(',')
        var page = []
        this.RightInfoList.map(item => {
          if (item.SuperNo === '') {
            item.son = []
            page.push(item)
          }
        })
        for (var i = 0; i < this.RightInfoList.length; i++) {
          for (var j = 0; j < page.length; j++) {
            if (this.RightInfoList[i].SuperNo === page[j].RightNo) {
              page[j].son.push(this.RightInfoList[i])
            }
          }
        }
        for (var i = 0; i < this.RightInfoList.length; i++) {
          if (this.RightInfoList[i].SuperNo === '') {
            this.originRoleData = Object.assign({}, this.originRoleData, {
              [this.RightInfoList[i].RightNo]: {
                RightNo: this.RightInfoList[i].RightNo,
                SuperNo: this.RightInfoList[i].SuperNo,
                RightName: this.RightInfoList[i].RightName,
                son: [],
                num: 0
              }
            })
          } else {
          }
        }
        this.RightInfoList.map(item => {
          if (item.SuperNo !== '') {
            this.originRoleData[item.SuperNo].son.push({
              RightNo: item.RightNo,
              SuperNo: item.SuperNo,
              RightName: item.RightName
            })
          }
        })
        this.SuperNoList = page
      })
    },
    Right(val) {
      if (val === true) {
        // 是超级管理员
        var objectValues = Object.values(this.originRoleData)
        objectValues.map(item => {
          this.parentRoleArr.push(item.RightNo)

          item.son.map(childItem => {
            this.childRoleObj.push({
              RightNo: childItem.RightNo,
              SuperNo: childItem.SuperNo,
              RightName: childItem.RightName
            })
            this.childRoleArr.push(childItem.RightNo)
          })
        })
      } else {
        this.childRoleArr = []
        this.parentRoleArr = []
        this.childRoleObj = []
      }
    }
  }
}
</script>

<style >
/* 提示框css */
  .test{
    max-height: 300px;
    max-width: 500px;
    font-size: 15px;
  }
</style>


